package com.downbox.service.impl;

import com.downbox.domain.User;
import com.downbox.dto.UserInfoResp;
import com.downbox.dto.UserStatsResp;
import com.downbox.repository.ContributionRepository;
import com.downbox.repository.DrawHistoryRepository;
import com.downbox.domain.QuotaDaily;
import com.downbox.repository.QuotaDailyRepository;
import com.downbox.repository.UserRepository;
import com.downbox.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private DrawHistoryRepository drawHistoryRepository;

    @Autowired
    private ContributionRepository contributionRepository;

    @Autowired
    private QuotaDailyRepository quotaDailyRepository;

    @Override
    public UserInfoResp getUserInfo(Long userId) {
        User user = getUserById(userId);
        UserInfoResp resp = new UserInfoResp();
        resp.setUid(user.getId());
        resp.setNickname(user.getNickname());
        resp.setCreatedAt(user.getCreatedAt());
        return resp;
    }

    @Override
    public UserStatsResp getUserStats(Long userId) {
        // 统计抽奖次数
        long totalDraws = drawHistoryRepository.countByUid(userId);
        // 统计投稿次数
        long totalContributions = contributionRepository.countByUid(userId);
        // 获取今日剩余奖励次数
        Integer bonusLeft = quotaDailyRepository.findByUidAndDate(userId, LocalDate.now())
                .map(QuotaDaily::getBonusLeft)
                .orElse(0);

        UserStatsResp resp = new UserStatsResp();
        resp.setTotalDraws((int) totalDraws);
        resp.setTotalContributions((int) totalContributions);
        resp.setBonusLeft(bonusLeft != null ? bonusLeft : 0);
        return resp;
    }

    @Override
    public User getUserById(Long userId) {
        return userRepository.findById(userId)
                .orElseGet(() -> {
                    // 用户不存在时自动创建
                    User newUser = new User();
                    newUser.setId(userId);
                    newUser.setNickname("用户" + userId);
                    newUser.setCreatedAt(LocalDateTime.now());
                    return userRepository.save(newUser);
                });
    }
}